package interfaces.batch.legacy.importlegacy.jenkins.batch;

import domain.model.project.Project;
import domain.model.project.ProjectRepository;
import infra.mongodb.MongoDBProjectRepository;
import org.springframework.batch.item.ItemWriter;
import util.mongodb.BasicMongoDBDataSource;

import java.util.List;

/**
 * @author Gregory Boissinot
 */
public class JobItemWriter implements ItemWriter<Project> {

    private final ProjectRepository projectRepository;

    public JobItemWriter() {
        projectRepository = new MongoDBProjectRepository(getMongoDBDataSource());
    }

    @Override
    public void write(List<? extends Project> projects) throws Exception {
        for (Project project : projects) {
            System.out.println(String.format("Writing '%s' project.", project.getProjectId().getName()));
            importProjectItem(project);
        }
    }

    public void importProjectItem(Project project) throws Exception {
        projectRepository.store(project);
    }


    private BasicMongoDBDataSource getMongoDBDataSource() {
        return new BasicMongoDBDataSource("localhost", 27017, "ci");
    }
}
